<script>
import { Input } from 'element-ui';
export default {
  name: 'NameInput',
  extends: Input,
  methods: {
    handleInput(event) {
      // 输入法
      if (this.isComposing) return;

      // 过滤无效字符
      const normValue = this.normalize(event.target.value)
      if (normValue != event.target.value) {
        event.target.value = normValue
      }

      // 更新
      if (event.target.value === this.nativeInputValue) return;
      this.$emit('input', event.target.value);
      this.$nextTick(this.setNativeInputValue);
    },
    normalize(originValue) {
      if (originValue) {
        let value = originValue
          .replace(/\s/g, '') // 去空白
          .replace(/[\uff01-\uff5e]/g, c => String.fromCharCode(c.charCodeAt(0) - 0xff00 + 0x0020)) // 全角转半角
          .replace(/[^\u0021-\u007f]/g, '') // 去ASC之外所有字符
        return value;
      } else {
        return originValue
      }
    }
  },
  watch: {
    value(newVal) {
      const normVal = this.normalize(newVal)
      if (normVal != newVal) {
        this.$emit('input', normVal);
        this.$nextTick(this.setNativeInputValue);
      }
    }
  }
}
</script>
